import os
import subprocess
import sys
import threading
import traceback
import psutil
import pyautogui
from pywinauto import Desktop, Application, timings
from pywinauto.keyboard import send_keys
import time
from pywinauto.timings import Timings
from config_logger import log
import uiautomation
from pywinauto.mouse import move, click
from send_message import Send
class VideoProcessor:
    def __init__(self, directory, app_path):
        self.directory = directory
        self.app_path = app_path

    def check_for_mp4(self, video_id):
        files = os.listdir(self.directory)
        for file in files:
            # if file.endswith('.mp4'):
            if file == f'{video_id}.mp4':
                return True
        return False

    def kill_processes_by_name(self, name):
        for proc in psutil.process_iter(attrs=['pid', 'name']):
            if proc.info['name'] == name:
                try:
                    proc.kill()
                    log.info(f"已终止进程 {proc.info['pid']}")
                except psutil.NoSuchProcess:
                    log.error(f"找不到进程 {proc.info['pid']}")
                except Exception as e:
                    log.error(f"终止进程 {proc.info['pid']} 时出错: {e}")

    
    def autoJy(self, task_id, video_id):
        try:
            start_time = time.time()  # 记录开始时间
            log.info("启动应用程序")
            subprocess.Popen(self.app_path)  # 使用 subprocess 启动应用程序
        except Exception as e:
            log.error(f"启动应用程序时出错: {e}")
            return False

        try:
            start_wait = time.time()
            # 使用 uiautomation 等待主窗口
            main_window = uiautomation.WindowControl(searchDepth=1, Name="剪映专业版")
            timeout = 18  # 设置超时时间
            while not main_window.Exists(0, 0) and time.time() - start_wait < timeout:
                time.sleep(0.1)  # 等待 0.1 秒

            if not main_window.Exists(0, 0):
                log.error("主窗口未在预期时间内出现")
                return False

            main_window.SetTopmost(True)  # 确保主窗口在前台
            end_time = time.time()  # 记录结束时间
            execution_time = end_time - start_time  # 计算执行时间
            log.info(f"已连接到主窗口,耗时：{execution_time}")
        except Exception as e:
            msg = traceback.format_exc()
            log.error(f"连接主窗口错误: {msg}")
            try:
                screenshot = pyautogui.screenshot()
                log.info(f"连接到主窗口出错保存截图{task_id}.png")
                screenshot.save(f"logs/连接到主窗口出错{task_id}.png")
            except BaseException as e:
                log.error(f"找或点击草稿目标控件时出错保存截图{task_id}.png失败：{e}")
            return False

        # 发送 ESC 键
        send_keys('{ESC}')  # 防止有弹窗

        try:
            root_path = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else os.path.dirname(
                os.path.abspath(__file__))
            img_path = os.path.join(root_path+r"\images", 'draft.png')
            
            # 添加图片路径的调试日志
            log.info(f"正在尝试读取图片，路径为: {img_path}")
            if not os.path.exists(img_path):
                log.error(f"找不到图片文件: {img_path}")
                # 尝试在当前工作目录查找图片
                img_path = os.path.join(os.getcwd(), 'draft.png')
                log.info(f"正在尝试备用图片路径: {img_path}")
                if not os.path.exists(img_path):
                    log.error(f"备用路径下也找不到图片: {img_path}")
                    return False

            # 添加超时逻辑
            start_time = time.time()
            timeout = 10  # 设置10秒超时时间
            center = None
            
            while time.time() - start_time < timeout:
                try:
                    center = pyautogui.locateCenterOnScreen(img_path, confidence=0.8)
                    if center is not None:
                        x, y = center
                        log.info("找到草稿按钮位置")
                        # 执行点击操作
                        click(coords=(x, y + 100))
                        break
                except pyautogui.ImageNotFoundException:
                    log.info("未找到图片，继续尝试...")
                    time.sleep(0.5)  # 每次尝试间隔0.5秒
                    continue
            
            if center is None:
                log.error(f"超过{timeout}秒未找到草稿图像")
                try:
                    screenshot = pyautogui.screenshot()
                    log.info(f"保存截图{task_id}.png")
                    screenshot.save(f"logs/{task_id}.png")
                except BaseException as e:
                    log.error(f"保存截图{task_id}.png失败：{e}")
                    self.kill_processes_by_name("JianyingPro.exe")
                return False

        except Exception as e:
            log.error(f"查找或点击草稿目标控件时出错: {e}")
            try:
                screenshot = pyautogui.screenshot()
                log.info(f"找或点击草稿目标控件时出错保存截图{task_id}.png")
                screenshot.save(f"logs/点击{task_id}草稿.png")
            except BaseException as e:
                log.error(f"找或点击草稿目标控件时出错保存截图{task_id}.png失败：{e}")
            return False

        time.sleep(2)
        try:
            if self.try_export(root_path):
                time.sleep(1)
                export_path = os.path.join(root_path+r"\images", 'confirmExport.png')
                center= self.wait_for_image(export_path)
                if center:
                    x, y = center
                    log.info("找到确认导出按钮并点击")
                    click(coords=(x, y))
                send_keys('{ENTER}')
                log.info("使用 send_keys 发送 Enter 键")
            else:
                try:
                    screenshot = pyautogui.screenshot()
                    log.info(f"保存截图{task_id}.png")
                    screenshot.save(f"logs/{task_id}.png")
                except BaseException as e:
                    log.error(f"保存截图{task_id}.png失败：{e}")
                    self.kill_processes_by_name("JianyingPro.exe")
                return False
        except Exception as e:
            log.error(f"使用 send_keys 发送 Enter 键时出错: {e}")
            return False

        num = 0
        while True:
            time.sleep(5)
            num += 1
            if self.check_for_mp4(video_id):
                log.info(f"目录中有 {video_id}.mp4")
                time.sleep(3)
                log.info("导出完成，开始退出")
                self.kill_processes_by_name("JianyingPro.exe")
                return True
            else:
                if num == 100:
                    Send.dingding(f"{video_id}太久了")
                if num < 180:
                    log.info(f"目录中没有 {video_id}.mp4")
                    send_keys('{ENTER}')
                    log.info("使用 send_keys 发送 Enter 键")
                    continue
                else:
                    try:
                        screenshot = pyautogui.screenshot()
                        log.info(f"保存截图{task_id}.png")
                        screenshot.save(f"logs/{task_id}.png")
                    except BaseException as e:
                        log.error(f"保存截图{task_id}.png失败：{e}")
                    self.kill_processes_by_name("JianyingPro.exe")
                    return False

    def wait_for_image(self, image_path, timeout=5, confidence=0.8):
        """等待图片出现并返回中心坐标"""
        start_time = time.time()
        while time.time() - start_time < timeout:
            try:
                center = pyautogui.locateCenterOnScreen(image_path, confidence=confidence)
                if center is not None:
                    return center
            except pyautogui.ImageNotFoundException:
                pass
            time.sleep(0.5)
        return None

    def try_export(self, root_path):
        """尝试打开导出窗口"""
        try:
            exportImg_path = os.path.join(root_path+r"\images", 'exportImg.png')
            exportWindow_path = os.path.join(root_path+r"\images", 'exportWindow.png')

            for _ in range(20):
                time.sleep(1)
                
                # 尝试通过图片点击导出
                center = self.wait_for_image(exportImg_path)
                if center:
                    log.info("找到导出按钮位置")
                    x, y = center
                    click(coords=(x, y))
                    
                # 尝试通过快捷键导出
                send_keys('^e')
                log.info("发送 Ctrl+E 键盘组合")
                
                # 检查导出窗口是否出现
                center = self.wait_for_image(exportWindow_path)
                if center:
                    log.info("导出窗口出现啦")
                    return True
                
                log.info("未找到导出窗口，继续尝试...")

            if os.path.exists(f"{self.directory}/.__jianying_export_temp_folder__"):
                return True

            return False

        except timings.TimeoutError:
            log.error("窗口在指定的超时时间内没有准备好")
            return False
        except Exception as e:
            msg = traceback.format_exc()
            log.error(f"导出操作时出错: {msg}")
            return False

if __name__ == '__main__':
    video_processor = VideoProcessor(directory=r"D:\剪映\导出", app_path=r"D:\剪映\JianyingPro\JianyingPro.exe")
    video_processor.autoJy(1,1)

